<template>
  <div style="padding: 24px 12px">
    <el-form inline>
      <el-form-item label="运行模式" size="small">
        <el-radio-group
          v-model="CEMStore.currentView.selectedMode"
          @change="handleRefresh"
        >
          <!-- @change="chartRefresh()" -->
          <el-radio-button :value="'auto'">
            <span>自动</span>
            <span v-if="selectedMode == 'auto'"> ({{ currentMode }})</span>
          </el-radio-button>
          <el-radio-button :value="'NN'">NN</el-radio-button>
          <el-radio-button :value="'NNWJ'">NNWJ</el-radio-button>
          <el-radio-button :value="'SS'">SS</el-radio-button>
          <el-radio-button :value="'SSWJ'">SSWJ</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="时间粒度" size="small">
        <el-radio-group
          v-model="CEMStore.currentView.timeStep"
          @change="handleRefresh"
        >
          <el-radio-button :value="1">15分钟</el-radio-button>
          <el-radio-button :value="2">30分钟</el-radio-button>
          <el-radio-button :value="4">60分钟</el-radio-button>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <transition name="el-fade-in">
      <el-table
        :data="recommendList"
        size="small"
        style="width: 100%"
        height="calc(100vh - 180px)"
        v-if="show"
      >
        <!-- <el-table-column type="expand">
          <template #default="props">
            <h3>Family</h3>
            <el-table :data="props.row.family" :border="childBorder">
              <el-table-column label="Name" prop="name" />
              <el-table-column label="State" prop="state" />
              <el-table-column label="City" prop="city" />
              <el-table-column label="Address" prop="address" />
              <el-table-column label="Zip" prop="zip" />
            </el-table>
          </template>
        </el-table-column> -->
        <el-table-column
          label="时刻"
          min-width="120"
          align="center"
          :resizable="false"
        >
          <template #default="scope">
            <div
              style="
                display: flex;
                align-items: center;
                justify-content: center;
              "
            >
              <el-icon><Calendar /></el-icon>
              <span style="margin-left: 3px">{{
                scope.row.moment.format("YYYY/MM/DD")
              }}</span>
            </div>
            <div
              style="
                display: flex;
                align-items: center;
                justify-content: center;
              "
            >
              <el-icon><Clock /></el-icon>
              <span style="margin-left: 3px"
                >{{ scope.row.moment.format("HH:mm") }}~{{
                  scope.row.moment.add(15 * timeStep, "minute").format("HH:mm")
                }}</span
              >
            </div>
            <!-- <el-text v-if="scope.row.current" type="success" size="small"
              >(当前)</el-text
            > -->
          </template>
        </el-table-column>
        <!-- <el-table-column label="扇区" prop="count" min-width="40" /> -->
        <el-table-column
          label="扇区数量"
          min-width="80"
          align="center"
          :resizable="false"
        >
          <template #default="scope">
            <span style="font-size: 18px; font-weight: bolder">{{
              scope.row.count
            }}</span>
            <span style="margin-left: 4px">扇区</span>
          </template>
        </el-table-column>
        <el-table-column
          label="组合"
          min-width="500"
          align="left"
          :resizable="false"
        >
          <template #default="scope">
            <div v-for="(models, index) in scope.row.areas" class="scheme-line">
              <!-- scheme -->
              <!-- areas -->
              <span style="margin-right: 4px">{{ index + 1 }}#</span>
              <!-- <span>{{ models.join(", ") }}</span> -->
              <span>{{ models.split(" / ")[1] }}</span>
              <!-- <span>{{ scope.row.details[scope.row.areas[index]] }}</span> -->
              <el-divider direction="vertical" />
              <el-button
                type="info"
                link
                size="small"
                style="margin: 0"
                @click="showDetail(scope.row.details[models])"
              >
                <!-- scope.row.details[scope.row.areas[index]] -->
                <el-icon><Comment /></el-icon>
              </el-button>
              <el-button
                type="info"
                link
                size="small"
                style="margin: 0"
                @click="
                  showDetail(scope.row.tagDetails[scope.row.areas[index]])
                "
              >
                <el-icon><Link /></el-icon>
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="备注"
          min-width="200"
          align="left"
          :resizable="false"
        >
          <template #default="scope">
            <div>
              <el-text type="warning" size="small" v-if="scope.row.overloaded">
                <el-icon><WarningFilled /></el-icon>
                <span style="margin-left: 3px">超量</span>
              </el-text>
              <el-text
                type="primary"
                size="small"
                v-else-if="scope.row.optimized"
              >
                <!-- <el-icon><QuestionFilled /></el-icon> -->
                <el-icon><SuccessFilled /></el-icon>
                <span style="margin-left: 3px">空闲</span>
              </el-text>
              <el-text type="success" size="small" v-else>
                <el-icon><SuccessFilled /></el-icon>
                <span style="margin-left: 3px">正常</span>
              </el-text>
            </div>
            <div>方案: {{ scope.row.title }}</div>
            <div>
              <span>
                评价:
                {{
                  Math.round(scope.row.evaluation.evaluationMixed * 100) / 100
                }}
              </span>
              <el-divider direction="vertical" />
              <el-button
                type="info"
                size="small"
                link
                @click="showDetail(scope.row.evaluation)"
              >
                <el-icon><Comment /></el-icon>
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </transition>
    <!-- <pre>{{ recommendList }}</pre> -->
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  computed,
  onMounted,
  onUnmounted,
  nextTick,
  h,
} from "vue";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import axios from "axios";
import dayjs from "dayjs";

import useFlowStore from "@/store/flow.js";
import useSeatStore from "@/store/seat.js";
import useActivityStore from "@/store/activity.js";
import useCommonStore from "@/store/common.js";
import useCEMStore from "@/store/CEM.js";

const flowStore = useFlowStore();
const seatStore = useSeatStore();
const activityStore = useActivityStore();
const commonStore = useCommonStore();
const CEMStore = useCEMStore();

const policyResult = computed(() => CEMStore.realCompute.policyResult);
const timeStep = computed(() => CEMStore.currentView.timeStep);
const selectedMode = computed(() => CEMStore.currentView.selectedMode);
const currentMode = computed(() =>
  CEMStore.currentView.selectedMode == "auto"
    ? activityStore.opMode
    : // seatStore.seatStatusFull.filter((cell) => cell.seatType == "运行方向")[0]
      //     .logicSectorCode +
      //   (activityStore.militaryStatus.filter((cell) =>
      //     (cell.arrField + cell.depField + cell.unit).includes("温江")
      //   ).length > 0
      //     ? "WJ"
      //     : "")
      CEMStore.currentView.selectedMode
);

const currentAdvice = computed(() =>
  policyResult.value
    ? policyResult.value.filter((item) => item.mode == currentMode.value)[0]
    : null
);

const recommendList = computed(() => {
  if (currentAdvice.value) {
    let result = currentAdvice.value.recommend.map((item, index, array) => {
      // let tagData = {};
      // flowStore.tags.forEach((tag, tagIndex) => {
      //   tagData[tag] = flowStore.rawData[index][tagIndex];
      // });
      let moment = dayjs(flowStore.begTime).add(15 * index, "minute");
      let current =
        dayjs().diff(moment) >= 0 && dayjs().diff(moment) < 15 * 60000;
      // console.log("recommendList", item);
      return {
        moment,
        current,
        title: item.title,
        count: item.areas.length,
        scheme: item.models,
        areas: item.areas,
        evaluation: item.evaluation,
        overloaded: currentAdvice.value.overloaded[index],
        optimized: currentAdvice.value.optimized[index],
        details: item.areaDetails,
        tagDetails: item.areaTagDetails,
      };
    });
    let startIndex = 0;
    for (let i = 0; i < result.length; i++) {
      if (
        timeStep.value == 4 &&
        result[i].moment.minute() == 0 &&
        dayjs().diff(result[i].moment, "minute") <= 60
      ) {
        startIndex = i;
        break;
      } else if (
        timeStep.value == 2 &&
        result[i].moment.minute() == 30 &&
        dayjs().diff(result[i].moment, "minute") <= 30
      ) {
        startIndex = i;
        break;
      } else if (dayjs().diff(result[i].moment, "minute") <= 15) {
        startIndex = i;
        break;
      }
    }
    console.log("recommendList", "startIndex", startIndex);
    if (timeStep.value == 4) {
      let result2 = new Array();
      for (let i = startIndex; i < result.length - 4; i += 4) {
        if (
          dayjs().diff(result[i].moment, "minute") <= 60 ||
          dayjs().diff(result[i].moment, "minute") < 0
        ) {
          // console.log("recommendList", result[i].moment.format("MM/DD HH:mm"));
          let count = result[i].count;
          let selectedIndex = i;
          if (count < result[i + 1].count) {
            count = result[i + 1].count;
            selectedIndex = i + 1;
          } else if (count < result[i + 2].count) {
            count = result[i + 2].count;
            selectedIndex = i + 2;
          } else if (count < result[i + 3].count) {
            count = result[i + 3].count;
            selectedIndex = i + 3;
          }
          let cell = JSON.parse(JSON.stringify(result[selectedIndex]));
          cell.moment = result[i].moment;
          cell.current =
            dayjs().diff(cell.moment, "minute") >= 0 &&
            dayjs().diff(cell.moment, "minute") < 60;
          result2.push(cell);
        }
      }
      return result2;
    } else if (timeStep.value == 2) {
      let result2 = new Array();
      for (let i = startIndex; i < result.length - 2; i += 2) {
        if (
          dayjs().diff(result[i].moment, "minute") <= 30 ||
          dayjs().diff(result[i].moment, "minute") < 0
        ) {
          // console.log("recommendList", result[i].moment.format("MM/DD HH:mm"));
          let count = result[i].count;
          let selectedIndex = i;
          if (count < result[i + 1].count) {
            count = result[i + 1].count;
            selectedIndex = i + 1;
          }
          let cell = JSON.parse(JSON.stringify(result[selectedIndex]));
          cell.moment = result[i].moment;
          cell.current =
            dayjs().diff(cell.moment, "minute") >= 0 &&
            dayjs().diff(cell.moment, "minute") < 30;
          result2.push(cell);
        }
      }
      return result2;
    } else {
      let result2 = new Array();
      for (let i = 0; i < result.length; i++) {
        if (
          dayjs().diff(result[i].moment) <= 15 * 60000 ||
          dayjs().diff(result[i].moment) < 0
        ) {
          result2.push(result[i]);
        }
      }
      return result2;
    }
  } else {
    return new Array();
  }
});

const show = ref(true);
const handleRefresh = async () => {
  show.value = false;
  await nextTick();
  show.value = true;
};

const showDetail = (item) => {
  ElMessageBox({
    title: "查看详细信息",
    message: h(
      "div",
      {
        style: {
          maxHeight: "calc(90vh - 200px)",
          overflow: "auto",
          fontFamily: "Consolas, 'Courier New', Courier, monospace",
        },
      },
      Array.isArray(item)
        ? h(
            "pre",
            { style: { lineHeight: "24px" } },
            JSON.stringify(item, null, 2)
          )
        : Object.keys(item).map((key) =>
            h(
              "div",
              { style: { lineHeight: "32px" } },
              `${key}: ${Math.round(item[key] * 100) / 100}`
            )
          )
    ),
    draggable: true,
  });
};
</script>

<style scoped>
.scheme-line {
  border-bottom: 1px dashed var(--el-border-color-extra-light);
}

.scheme-line:last-child {
  border-bottom: none;
}
</style>
